package com.demo.util;


import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Arrays;

public class MidUtil {
    /**
     * 生成mid文件
     * @param note
     * @param pitch
     * @param meter
     * @param component
     * @param tone
     * @param path 生成路径
     * @return
     */
    public static String genMid(String[]note,String[]pitch,String[]meter,String[]component,String tone,String path){
        try {
            File file=new File(path);
            //拿到音频文件夹路径
            File audioFolder=file.getParentFile();
            //如果么有文件夹就创建
            if (!audioFolder.exists() && !audioFolder.isDirectory()) {
                audioFolder.mkdirs();
            }
            String[] args = new String[] { "python", "D:\\java\\project\\music\\src\\main\\resources\\test.py", Arrays.toString(note),Arrays.toString(pitch),Arrays.toString(meter),Arrays.toString(component),tone,path};
            Process proc = Runtime.getRuntime().exec(args);// 执行py文件
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * mid文件转换为wav文件
     * @param midPath mid文件路径
     * @param wavPath wav文件路径
     */
    public static void mid2Wav(String midPath,String wavPath){
        try {
            AudioInputStream audioInputStream= AudioSystem.getAudioInputStream(new File(midPath));
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE,new File(wavPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
